package com.lkm.market2_0.m.dataUp;

import com.lkm.frame.P;
import com.lkm.frame.task.StopAble;
import com.lkm.javatool.lang.NameValueP;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Request.Builder;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.net.CookieManager;
import java.net.CookiePolicy;
import java.util.concurrent.TimeUnit;




public class SZHttpRequest {
    private static OkHttpClient client = new OkHttpClient();

    static{
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        client.setCookieHandler(cookieManager);
        client.setConnectTimeout(30, TimeUnit.SECONDS);
        client.setReadTimeout(100,TimeUnit.SECONDS);
        client.setWriteTimeout(100,TimeUnit.SECONDS);
    }
    public static   OkHttpClient getHttpClient(){
        if(client.getCache()==null) {
            //P.d("=====client.getCache()==null");
            
//			client.setCache(new Cache(new File(Config.getHttpFileCache(MyApplicationBase.application)), 1024 * 1024 * 20));
        }
        return client;

    }



//        System.out.println(getString(null, "https://dev.balance.api.satrace.cn/", new NameValueP[]{



    public static String getApiInfo(String url, NameValueP[] params){
        String logParam = "";
        if (params != null) {
            for (NameValueP n : params) {
                if (n != null && n.getName() != null && n.getValue() != null)
                    logParam += "&" + n.getName() + "=" + n.getValue();
            }

        }
        String apiInfo=url + logParam;
        return apiInfo;
    }
    public static String sentContent(  String url, String content, StopAble sa) {

        String resulrStr = null;
        try {

            RequestBody body = RequestBody.create(MediaType.parse("application/x-www-form-urlencoded"),content);

            Builder requestBuilder = new Builder().url(url);

            requestBuilder.post(body);

            Request request = requestBuilder.build();


            final Call call = getHttpClient().newCall(request);
            if (sa != null) {
                final Runnable oldCancelRun = sa.getCancelObserver();
                sa.setCancelObserver(new Runnable() {
                    @Override
                    public void run() {
                        if (oldCancelRun != null)
                            oldCancelRun.run();
                        call.cancel();
                    }
                });
            }

            Response response = call.execute();

            try {
                resulrStr = response.body().string();
            } catch (Exception e) {
                resulrStr = null;
                e.printStackTrace();
            }

        } catch (Exception e) {
            resulrStr = null;
            e.printStackTrace();

        }
        return resulrStr;
    }
    

    public static String getString( String url, NameValueP[] params,boolean isFileUploadForm, StopAble sa) {
//        System.out.println("=======url " +url);

        String resulrStr = null;
        try {

            RequestBody body = null;
            if(!isFileUploadForm) {
                FormEncodingBuilder feb = new FormEncodingBuilder();
                if (params != null) {
                    for (NameValueP n : params) {
                        if (n != null && n.getName() != null && n.getValue() != null)
                            feb.add(n.getName(), n.getValue());
                    }
                }

                try {
                    if (feb != null)
                        body = feb.build();
                } catch (Exception e) {
                    body = null;
                }

            }else{

                MultipartBuilder feb = new MultipartBuilder();
//                feb.addPart( Headers.of("Content-Disposition", "form-data; name=\"file\";filename=\"file.jpg\""),
//                        RequestBody.create(MediaType.parse("image/png"),"")

                feb.addFormDataPart("lkmk", "");
                if (params != null) {
                    for (NameValueP n : params) {
                        if (n != null && n.getName() != null && n.getValue() != null)
                            feb.addFormDataPart(n.getName(), n.getValue());
                    }

                }

                try {
                    if (feb != null)
                        body = feb.build();
                } catch (Exception e) {
                    e.printStackTrace();
                    body = null;
                }
            }




            Builder requestBuilder = new Builder().url(url);

            requestBuilder.post(body);

            Request request = requestBuilder.build();

            final Call call = getHttpClient().newCall(request);
            if (sa != null) {
                final Runnable oldCancelRun = sa.getCancelObserver();
                sa.setCancelObserver(new Runnable() {
                    @Override
                    public void run() {
                        if (oldCancelRun != null)
                            oldCancelRun.run();
                        call.cancel();
                    }
                });
            }



            Response response = call.execute();

//			for (Certificate certificate : response.handshake().peerCertificates()) {
//				System.out.println(CertificatePinner.pin(certificate));

            try {
                resulrStr = response.body().string();
            } catch (Exception e) {
                resulrStr = null;
                e.printStackTrace();
            }

        } catch (Exception e) {
            resulrStr = null;
            e.printStackTrace();
            System.out.println("=====sz " + e.getMessage());
        }
        return resulrStr;
    }


    static {
        OkHttpClient client = getHttpClient();
        CookieManager cookieManager = new CookieManager();
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        client.setCookieHandler(cookieManager);




//            setCertificates(Config.instance.getHttpsCertificates());





//                        .add("dev.balance.api.satrace.cn", "sha1
////                        .add("dev.balance.api.satrace.cn", "sha1/SXxoaOSEzPC6BgGmxAt/EAcsajw=")
////                        .add("publicobject.com", "sha1/blhOM3W9V/bVQhsWAcLYwPU6n24=")
////                        .add("publicobject.com", "sha1/T5x9IXmcrQ7YuQxXnxoCmeeQ84c=")


    }

    public static synchronized void clearCookie() {
        ((CookieManager) getHttpClient().getCookieHandler()).getCookieStore().removeAll();
    }



}
